// 成就状态管理
import AchievementService from '../services/achievement'

const state = {
  userAchievements: {},
  unlockedCount: 0
}

const mutations = {
  // 初始化用户成就数据
  INIT_ACHIEVEMENTS(state, payload) {
    state.userAchievements = payload || {}
    state.unlockedCount = Object.values(payload).filter(a => a.completed).length
  },

  // 更新成就状态
  UPDATE_ACHIEVEMENT(state, {key, count}) {
    const achievement = state.userAchievements[key] || {
      completed: false,
      count: 0,
      timestamp: null
    }
    
    achievement.count += count
    
    // 检查是否解锁新成就
    if (!achievement.completed && 
        AchievementService.isRequirementMet(key, achievement.count)) {
      achievement.completed = true
      achievement.timestamp = Date.now()
      state.unlockedCount++
    }
    
    state.userAchievements[key] = achievement
  }
}

const actions = {
  // 加载用户成就数据
  async loadAchievements({commit}, userId) {
    try {
      // 调用后端API获取成就数据
      const res = await uni.request({
        url: '/api/achievements',
        method: 'GET',
        data: { userId }
      })
      // 确保API返回格式与云函数一致
      const achievements = res.data.data || res.data
      commit('INIT_ACHIEVEMENTS', achievements)
    } catch (e) {
      console.warn('使用本地成就数据:', e)
      // API失败时使用本地mock数据
      const mockData = AchievementService.achievements.reduce((acc, ach) => {
        acc[ach.key] = {
          completed: false,
          count: 0,
          timestamp: null
        }
        return acc
      }, {})
      commit('INIT_ACHIEVEMENTS', mockData)
    }
  },

  // 更新成就进度
  async updateAchievement({commit}, {key, count = 1}) {
    commit('UPDATE_ACHIEVEMENT', {key, count})
    
    // 尝试同步到后端
    try {
      await uni.request({
        url: '/api/achievements/update',
        method: 'POST',
        data: { key, count }
      })
    } catch (e) {
      console.warn('成就数据本地更新:', e)
      // API失败时仅本地更新
    }
  }
}

const getters = {
  // 获取所有成就状态
  allAchievements: state => AchievementService.getAllAchievements(),
  
  // 获取已解锁成就数量
  unlockedCount: state => state.unlockedCount,
  
  // 获取成就完成百分比
  completionRate: state => {
    const total = AchievementService.achievements.length
    return total > 0 ? Math.round((state.unlockedCount / total) * 100) : 0
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
